import json
from datetime import datetime

from extensions import db

class Word(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    word = db.Column(db.String(100), nullable=False)
    type = db.Column(db.String(20), nullable=False)  # word/phrase/sentence
    phonetic = db.Column(db.String(100))
    meaning = db.Column(db.Text, nullable=False)
    example = db.Column(db.Text)
    difficulty = db.Column(db.String(20))  # easy/medium/hard
    status = db.Column(db.String(20), default='new')  # new/learning/learned/mastered
    last_reviewed = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'word': self.word,
            'type': self.type,
            'phonetic': self.phonetic,
            'meaning': self.meaning,
            'example': self.example,
            'difficulty': self.difficulty,
            'status': self.status,
            'lastReviewed': self.last_reviewed.isoformat() if self.last_reviewed else None,
            'createdAt': self.created_at.isoformat()
        }

class WordDefinition(db.Model):
    __tablename__ = 'word_definition'

    id = db.Column(db.Integer, primary_key=True)
    word = db.Column(db.String(100), unique=True, nullable=False)
    type = db.Column(db.String(20), nullable=False, default='word')  # word/phrase/sentence
    meaning = db.Column(db.Text, nullable=True)
    phonetics = db.Column(db.Text)  # 存储JSON字符串
    example = db.Column(db.Text)  # 存储为JSON字符串
    difficulty = db.Column(db.String(20), default='medium')
    status = db.Column(db.String(20), default='new')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def __repr__(self):
        return f'<WordDefinition {self.word}>'

    def set_example(self, sentence, translation):
        self.example = json.dumps({
            'sentence': sentence,
            'translation': translation
        })

    def get_example(self):
        return json.loads(self.example) if self.example else None

    # 新增序列化方法
    def set_phonetics(self, data):
        self.phonetics = json.dumps(data) if data else None

    # 新增反序列化方法
    def get_phonetics(self):
        return json.loads(self.phonetics) if self.phonetics else []

    def to_dict(self):
        return {
            'id': self.id,
            'word': self.word,
            'type': self.type,
            'meaning': self.meaning,
            'phonetic': self.phonetic,
            'example': self.get_example(),
            'difficulty': self.difficulty,
            'status': self.status,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }